package cn.arnold.offer.xingye;

public class Solution {
    public static void main(String[] args) {
        String number = "1";
        System.out.println(toBinary(number));
        System.out.println(toSixteen(number));
    }

    public static String changeFormatNumber(String number) {
        int max = (int) Math.pow(2, 15) - 1; //最大值
        int min = -(int) Math.pow(2, 15);  //最小值
        if (Integer.parseInt(number) > max || Integer.parseInt(number) < min) {
            return "NODATA";
        }
        if (!isNumber(number)) {
            return "INPUTERROR";
        }
        String s1 = toBinary(number);
        String s2 = toSixteen(number);
        return s1 + "," + s2;
    }

    //10进制转为2进制
    public static String toBinary(String s) {
        int n = Integer.parseInt(s);
        //先转为正数
        if (n<0){
            n = Integer.parseInt(s.substring(1,s.length()));
        }
        StringBuilder sb = new StringBuilder();
        while (n != 0) {
            int temp = n % 2;
            sb.insert(0, temp);
            n = n / 2;
        }
        String str = sb.toString();
        int m = str.length();
        if (m != 16) {
            for (int i = 0; i < 16 - m; i++) {
                str = "0" + str;
            }
        }
        if (n>0){
            return str;
        }else {
            return str;
        }


    }

    //10进制转为16进制
    public static String toSixteen(String s) {
        int n = Integer.parseInt(s);
        String str = "";
        while (n != 0) {
            int temp = n % 16;
            if (temp <= 9 && temp >= 0) {
                str = (char) (temp + '0') + str;
            } else {
                str = (char) (temp - 10 + 'A') + str;
            }
            n = n / 16;
        }
        int m = str.length();
        if (m != 4) {
            for (int i = 0; i < 4 - m; i++) {
                str = "0" + str;
            }
        }
        return str;
    }

    //字符串是否为数字
    public static boolean isNumber(String number) {
        for (int i = 0; i < number.length(); i++) {
            if (!Character.isDigit(number.charAt(i))) {
                return false;
            }
        }
        return true;
    }
}
